<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row>
      <!-- 部门树 -->
      <!-- <el-col :lg="4" :xs="24" class="mb-[12px]">
        <DeptTree v-model="queryParams.deptId" @node-click="handleQuery" />
      </el-col> -->

      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="queryParams.username" placeholder="用户名" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="电话" clearable style="width: 200px" 
                @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="queryParams.email" placeholder="邮箱" clearable style="width: 200px" 
                @keyup.enter="handleQuery"/>
            </el-form-item>
            <!-- <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="用户名/昵称/手机号"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="全部"
                clearable
                class="!w-[100px]"
              >
                <el-option label="正常" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <div class="flex-x-between mb-10px">
            <div>
              <el-button type="success" icon="plus" v-hasPerm="'sys_user_add'" @click="handleOpenDialog()">新增</el-button>
              <el-button type="danger" icon="delete" v-hasPerm="'sys_user_del'" :disabled="!selectIds.length" @click="handleDelete()">
                删除
              </el-button>
            </div>
            <div>
              <el-button icon="upload" v-hasPerm="'sys_user_export'" @click="handleOpenImportDialog">导入</el-button>
              <el-button icon="download" v-hasPerm="'sys_user_export'" @click="handleExport">导出</el-button>
            </div>
          </div>

          <el-table v-loading="loading" :data="pageData" height="calc(100vh - 350px)" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户名" width="120" prop="username" />
            <!-- <el-table-column label="用户id" prop="userId" /> -->
            <el-table-column label="昵称" width="120" align="center" prop="name" />
            <!-- <el-table-column label="性别" width="100" align="center">
              <template #default="scope">
                <DictLabel v-model="scope.row.gender" code="gender" />
              </template>
            </el-table-column> -->
            <el-table-column label="所属单位" min-width="200" align="center" prop="companyNames" show-overflow-tooltip></el-table-column>
            <el-table-column label="手机号码" align="center" prop="phone" width="120" show-overflow-tooltip/>
            <el-table-column label="邮箱" align="center" prop="email" min-width="160" show-overflow-tooltip/>
            <el-table-column label="状态" align="center" prop="lockFlag" width="80">
              <template #default="scope">
                <el-tag :type="lockTag[scope.row.lockFlag]">
                  {{ lockMap[scope.row.lockFlag] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="角色" align="center" prop="roleNames" width="130" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ scope.row.roleNames }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
            <el-table-column label="操作" fixed="right" width="268">
              <template #default="scope">
                <el-button type="primary" icon="RefreshLeft" size="small" link v-hasPerm="'sys_user_edit'" @click="hancleResetPassword(scope.row)">
                  重置密码
                </el-button>
                <el-button type="primary" icon="edit" link size="small" v-hasPerm="'sys_user_edit'" @click="handleOpenDialog(scope.row.userId)">
                  编辑
                </el-button>
                <el-button type="warning" :icon="scope.row.lockFlag == 0 ? 'Unlock' : 'Lock'" link size="small"
                  v-hasPerm="['sys_user_lock','sys_user_unlock']" @click="lockOp(scope.row)">
                  {{ scope.row.lockFlag == 0 ? '锁定' : '解锁' }}
                </el-button>
                <el-button type="danger" icon="delete" link size="small" v-hasPerm="'sys_user_del'" @click="handleDelete(scope.row.userId)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pager">
            <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户表单 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body :size="drawerSize"
      @close="handleCloseDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" :readonly="!!formData.userId" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item v-if="!formData.userId" label="密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item label="用户昵称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户昵称" />
        </el-form-item>

        <el-form-item label="所属单位" prop="companyIdsArr">
          <el-select v-model="formData.companyIdsArr" :filterable="true" clearable multiple placeholder="请选择">
            <el-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="所属区域" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            placeholder="请选择所属区域"
            :data="deptOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <Dict v-model="formData.gender" code="gender" />
        </el-form-item> -->

        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" multiple placeholder="请选择">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>

        <el-form-item label="状态" prop="lockFlag">
          <el-switch v-model="formData.lockFlag" inline-prompt active-text="正常" inactive-text="锁定" active-value="0"
            inactive-value="9" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="pwdDialog.visible" :title="pwdDialog.title" width="500" :close-on-click-modal="false">
      <div class="pwdStr">{{ passwordForm.pwdStr }}</div>
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="90px">
        <el-form-item label="原密码" prop="password">
          <el-input v-model="passwordForm.password" placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newpassword1">
          <el-input v-model="passwordForm.newpassword1" placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" placeholder="请输入确认密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="cancel">取消</el-button>
          <el-button size="small" type="primary" @click="confirm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入 -->
    <UserImport v-model="importDialogVisible" type="user" @import-success="handleQuery()" />
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from '@/store/modules/app.store';
import { DeviceEnum } from '@/enums/settings/device.enum';

import UserAPI, { UserForm, UserPageQuery, UserPageVO } from '@/api/system/user.api';
import UnitApi from '@/api/system/unit.api';
import RoleAPI from '@/api/system/role.api';

// import DeptTree from './components/DeptTree.vue';
import UserImport from './components/UserImport.vue';

defineOptions({
  name: 'User',
  inheritAttrs: false,
});

// 锁定状态 0-正常 9-锁定
const lockTag: any = {
  0: 'success',
  9: 'danger',
};
const lockMap: any = {
  0: '正常',
  9: '锁定',
};

const appStore = useAppStore();

const queryFormRef = ref();
const userFormRef = ref();
const passwordFormRef = ref();

const queryParams = reactive<UserPageQuery>({
  pageNum: 1,
  pageSize: 10,
  username: undefined,
  phone: undefined,
  email: undefined,
});
const total = ref(0);
const pageData = ref<UserPageVO[]>();
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: '新增用户',
});
const pwdDialog = reactive({
  visible: false,
  title: '重置密码',
});
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? '600px' : '90%'));

const formData = reactive<UserForm>({
  username: '',
  password: null,
  name: '',
  email: '',
  phone: '',
  role: [], // 角色id集合 (传给后端)
  companyIdsArr: [], // 所属单位id集合 前端绑定使用
  companyIds: '', // 所属单位id, 多个用逗号分隔 (传给后端)
  // status: 1,
  lockFlag: '0',
});

const rules = reactive({
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  // deptId: [{ required: true, message: '所属区域不能为空', trigger: 'blur' }],
  role: [{ required: true, message: '用户角色不能为空', trigger: 'blur' }],
  companyId: [{ required: true, message: '所属单位不能为空', trigger: 'change' }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      /*
        ^1：以1开头
        [3-9]：第二位为3-9之间的数字
        \d：后面跟着任意数字
        {9}：重复9次
        \d{9}：后续9位任意数字
        总长度11位，匹配大多数在用的手机号
      */
      pattern: /^1[3-9][0-9]\d{8}$/, // /^1(3\d|4[5-9]|5[0-35-9]|6[6]|7[0-35-8]|8\d|9[1-9])\d{8}$/
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
});

const passwordForm = reactive({
  userId: '',
  pwdStr: '',
  password: null,
  newpassword1: null,
  confirmPassword: null,
});
const passwordRules = reactive({
  password: [{ required: true, message: '原密码不能为空', trigger: 'blur' }],
  newpassword1: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
  ],
});
// 选中的用户ID
const selectIds = ref<string[]>([]);
// 单位下拉数据
const unitOptions = ref<any>([]);
// 部门下拉数据源
const deptOptions = ref<any[]>([]);
// 角色下拉数据源
const roleOptions = ref<any[]>([]);
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
async function handleQuery() {
  loading.value = true;
  const params = {
    current: queryParams.pageNum,
    size: queryParams.pageSize,
    username: queryParams.username,
    phone: queryParams.phone,
    email: queryParams.email,
  };
  UserAPI.getPage(params)
    .then((data) => {
      pageData.value = data.records.map((item) => {
        return {
          ...item,
          roleNames: item.roleList?.map((child) => child.roleName).join(','),
          companyNames: item.companyList?.map((child) => child.name).join(','),
        };
      });
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.deptId = undefined;
  queryParams.createTime = undefined;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.userId);
}

// 重置密码
function hancleResetPassword(row: UserPageVO) {
  ElMessageBox.confirm(
    '确认重置用户【' + row.username + '】的密码(有手机则为手机，无则为123456)',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      UserAPI.resetPassword(row.userId)
        .then((data) => {
          ElMessage.success('密码重置成功!');
        })
        .catch((err) => { });
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });

  // passwordForm.pwdStr = '请输入用户【' + row.username + '】的新密码';
  // passwordForm.userId = row.userId;
  // pwdDialog.visible = true;
  // ElMessageBox.prompt('请输入用户【' + row.username + '】的新密码', '重置密码', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  // }).then(
  //   ({ value }) => {
  //     if (!value || value.length < 6) {
  //       ElMessage.warning('密码至少需要6位字符，请重新输入');
  //       return false;
  //     }
  //     UserAPI.resetPassword({ userId: row.userId, newpassword1: value }).then(() => {
  //       ElMessage.success('密码重置成功，新密码是：' + value);
  //     });
  //   },
  //   () => {
  //     ElMessage.info('已取消重置密码');
  //   }
  // );
}

const cancel = () => {
  pwdDialog.visible = false;
  passwordFormRef.value.resetFields();
};
const confirm = () => {
  passwordFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (passwordForm.confirmPassword != passwordForm.newpassword1) {
        ElMessage.error('两次密码不一致');
        return false;
      }
      // UserAPI.resetPassword({
      //   userId: passwordForm.userId,
      //   password: passwordForm.password,
      //   newpassword1: passwordForm.newpassword1,
      // })
      //   .then((data) => {
      //     ElMessage.success('密码重置成功，新密码是：' + passwordForm.newpassword1);
      //   })
      //   .catch((err) => {
      //     console.log('err----', err);
      //   });
    }
  });
};
/**
 * 打开弹窗(新增/修改)
 *
 * @param userId 用户ID
 */
function handleOpenDialog(userId?: string) {
  dialog.visible = true;
  if (userId) {
    dialog.title = '修改用户';
    UserAPI.getFormDataById(userId).then((data: any) => {
      const roleIds = data.roleList.map((item: any) => item.roleId);
      const companyIdsArr = data.companyList.map((item: any) => item.id); // companyList 获取用
      formData.role = roleIds;
      formData.companyIdsArr = companyIdsArr;
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = '新增用户';
  }
}
const initRoleUnitOptions = () => {
  // 加载角色下拉数据源
  RoleAPI.getOptions()
    .then((data: any) => {
      roleOptions.value = data.map((item: any) => {
        return {
          label: item.roleName,
          value: item.roleId,
          roleCode: item.roleCode,
        };
      });
    })
    .catch((err) => { });
  // 加载单位下拉数据源
  UnitApi.getAllList()
    .then((data: any) => {
      unitOptions.value = data.map((item: any) => {
        return {
          label: item.name,
          value: item.id,
          code: item.code,
        };
      });
    })
    .catch((err) => { });
};
const getAllOptions = () => {
  Promise.all([RoleAPI.getOptions(), UnitApi.getAllList()])
    .then((res: any) => {
      console.log('res-', res);
      roleOptions.value = res[0].map((item: any) => {
        return {
          label: item.roleName,
          value: item.roleId,
        };
      });
      // 加载单位下拉数据源
      unitOptions.value = res[1].map((item: any) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
    })
    .catch((err) => { });
};
// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.userId = undefined;
  // formData.status = 1;
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.userId;
      loading.value = true;

      const params = JSON.parse(JSON.stringify(formData));
      params.companyIds = params.companyIdsArr.join(',');
      delete params.companyIdsArr;
      if (userId) {
        UserAPI.update(params)
          .then(() => {
            ElMessage.success('修改用户成功');
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.create(params)
          .then(() => {
            ElMessage.success('新增用户成功');
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 200);

const lockOp = (row: any) => {
  loading.value = true;
  const API = row.lockFlag == 0 ? UserAPI.lockUser : UserAPI.unlockUser;
  API(row.username)
    .then(() => {
      ElMessage.success(`${row.lockFlag == 0 ? '锁定' : '解锁'}成功!`);
      handleQuery();
    })
    .catch((err) => {
      loading.value = false;
      console.log('lockerr-', err);
    });
};
/**
 * 删除用户
 *
 * @param userId  用户ID
 */
function handleDelete(userId?: string) {
  const userIds = userId ? [userId] : selectIds.value;
  if (!userIds.length) {
    ElMessage.warning('请勾选删除项');
    return;
  }

  ElMessageBox.confirm('确认删除用户?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      loading.value = true;
      UserAPI.deleteByIds(userIds)
        .then(() => {
          ElMessage.success('删除成功');
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

// 导出用户
function handleExport() {
  const params = {
    username: queryParams.username,
    phone: queryParams.phone,
    email: queryParams.email,
  };
  UserAPI.export(params).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(response.headers['content-disposition'].split(';')[1].split('=')[1]);
    const fileType =
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8';

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement('a');
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

onMounted(() => {
  handleQuery();
  initRoleUnitOptions();
});
</script>

<style lang="scss" scoped>
.pwdStr {
  margin-bottom: 15px;
}
</style>
